import {Fragment, PureComponent} from 'react';
import {
  Card,
  Divider,
  Popconfirm,
  Form,
  Row,
  Col,
  Input,
  Button,
  Modal,
  message,
  Select,
  Tag
} from 'antd';
import React from 'react';
import Icon, {EditOutlined} from '@ant-design/icons';
import {connect} from "umi";
import {formatMessage} from "@@/plugin-locale/localeExports";
import ProTable from '@ant-design/pro-table';
import styles from '../common.less';
import {hasPermission, nopermission} from "@/hasPermission";
const { Option } = Select;
const { TextArea } = Input;


class Dictionary extends PureComponent{

  state = {
    formValues: {},
    updateFormValues: {},
    currentPage: 1,
    pageSize: 10,
    modalVisible: false
  }

  columns = [
    {
      title: formatMessage({ id: 'app.dictionary.name' }),
      dataIndex: 'name',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.dictionary.code' }),
      dataIndex: 'code',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.dictionary.value' }),
      dataIndex: 'value',
      align: 'center',
      render: text => text && text.split(',').map((item) => <Tag>{item}</Tag>)
    },
    {
      title: formatMessage({ id: 'app.dictionary.desc' }),
      dataIndex: 'desc',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.dictionary.loginName' }),
      dataIndex: 'loginName',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.dictionary.createTime' }),
      dataIndex: 'createTime',
      align: 'center'
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: '250px',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>
            <EditOutlined />
            {formatMessage({ id: 'app.common.edit' })}
          </a>
          <Divider type='vertical' />
          <Popconfirm
          title={formatMessage({ id: 'app.common.confirm-delete' })}
          onConfirm={() => this.handleDelete(record.id)}
          >
          <a>
          <Icon type='delete' />
          {formatMessage({ id: 'app.common.delete' })}
          </a>
          </Popconfirm>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'dictionary/fetch'
    })
    this.formRef = React.createRef();
    this.formRef2 = React.createRef();
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
      currentPage: pagination.current,
      pageSize: pagination.pageSize
    };
    if (sorter.field && sorter.order) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.setState({ currentPage: pagination.current, pageSize: pagination.pageSize });
    dispatch({
      type: 'dictionary/fetch',
      payload: params
    });
  };

  handleSearch = e => {
    const { dispatch } = this.props;
    const values = {
      ...e
    };
    this.setState({
      formValues: values
    });
    if (e == null) {
      values.currentPage = this.state.currentPage;
      values.pageSize = this.state.pageSize;
    } else {
      values.currentPage = 1;
      values.pageSize = 10;
    }
    dispatch({
      type: 'dictionary/fetch',
      payload: values
    });
  };

  handleFormReset = () => {
    const { dispatch } = this.props;
    this.formRef.current.resetFields();
    this.setState({
      formValues: {},
      currentPage: 1,
      pageSize: 10
    });
    dispatch({
      type: 'dictionary/fetch'
    });
  };

  handleModalVisible = (flag, value) =>{
    this.setState({
      modalVisible: !!flag,
      updateFormValues: value || null
    });
  }

  handleUpdate = () => {
    if (!hasPermission('admin:update')){
      nopermission();
      return;
    }
    const { dispatch } = this.props;
    let values = this.formRef2.current.getFieldsValue();
    let value = '';
    if (values.value.length > 0){
      values.value.map((item) => {
        value += item + ',';
      })
      let reg=/,$/gi;
      value = value.replace(reg,"");
    }
    values.value = value;
    if (values.id){
      dispatch({
        type: 'dictionary/updateDictionary',
        payload: {
          ...values
        }
      }).then(res => {
        if (res.status == 200){
          message.success('修改成功！');
          this.handleModalVisible();
          this.handleSearch();
        }
      })
    }else {
      dispatch({
        type: 'dictionary/addDictionary',
        payload: {
          ...values
        }
      }).then(res => {
        if (res.status == 200){
          message.success('新增成功！');
          this.handleModalVisible();
          this.handleSearch();
        }
      })
    }
  }

  handleDelete = id => {
    if (!hasPermission('admin:delete')){
      nopermission();
      return;
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'dictionary/deleteById',
      payload: {
        id: id
      }
    }).then(res => {
      if (res.status == 200){
        message.success('删除成功！');
        this.handleSearch();
      }
    })
  }

  renderSimpleForm() {

    return (
      <Form ref={this.formRef} onFinish={this.handleSearch}>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={7} sm={24} offset={1}>
            <Form.Item label={formatMessage({ id: 'app.dictionary.name' })} name='name'>
              <Input />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <Form.Item label={formatMessage({ id: 'app.dictionary.code' })} name='code'>
              <Input />
            </Form.Item>
          </Col>
          <Col md={7} sm={24}>
            <span className={styles.submitButtons} style={{textAlign: 'right'}}>
              <Button type='primary' onClick={() => this.handleModalVisible(true,null)}>
                {formatMessage({ id: 'app.common.add' })}
              </Button>
              <Button style={{ marginLeft: 8 }} type='primary' htmlType='submit'>
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type='primary'
              >
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  renderModalContent = values => {
    return (
      <Form ref={this.formRef2}>
        <Row>
          <Col span={11}>
            <Form.Item initialValue={values ? values.name : ''} label={formatMessage({ id: 'app.dictionary.name' })} name='name'>
              <Input style={{ width: '100%' }}/>
            </Form.Item>
          </Col>
          <Col span={11} offset={1}>
            <Form.Item initialValue={values ? values.code : ''} label={formatMessage({ id: 'app.dictionary.code' })} name='code'>
              <Input style={{ width: '100%' }}/>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={22}>
            <Form.Item initialValue={values ? values.value.split(',') : []} label={formatMessage({ id: 'app.dictionary.value' })} name='value'>
              <Select
                mode="tags"
                allowClear
                style={{ width: '100%' }}
                defaultValue={values ? values.value.split(',') : []}
              >
                {values && values.value.split(',').map((item) => <Option key={item}>{item}</Option>)}
              </Select>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col span={24}>
            <Form.Item initialValue={values ? values.desc : ''} label={formatMessage({ id: 'app.dictionary.desc' })} name='desc'>
              <TextArea rows={3} />
            </Form.Item>
          </Col>
        </Row>
        {values &&
        <Row style={{ display: 'none'}}>
          <Col span={24}>
            <Form.Item initialValue={values.id} name='id'>
              <Input hidden={true}/>
            </Form.Item>
          </Col>
        </Row>}
      </Form>
    )
  }

  render() {
    const {
      dictionary: { data },
      loading
    } = this.props;
    const { modalVisible, updateFormValues } = this.state;
    return (
      <>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
          <ProTable
            bordered={true}
            search={false}
            rowKey={record => record.id}
            loading={loading}
            dataSource={data ? data.list : []}
            pagination={data ? data.pagination : {}}
            columns={this.columns}
            onChange={this.handleBasicTableChange}
            options={{
              density: true,
              reload: () => {
                this.handleSearch();
              },
              fullScreen: true,
              setting: true
            }}
          />
        </div>
      </Card>
      {modalVisible &&
        <Modal
          destroyOnClose
          width={650}
          bodyStyle={{ paddingBottom: 0, paddingTop: 20 }}
          title={updateFormValues ? formatMessage({ id: 'app.dictionary.update' }) : formatMessage({ id: 'app.dictionary.add' })}
          visible={modalVisible}
          onOk={this.handleUpdate}
          onCancel={() => this.handleModalVisible(false, null)}
          afterClose={() => this.handleModalVisible()}
        >
          {this.renderModalContent(updateFormValues)}
        </Modal>
      }
      </>
    )
  }
}

export default connect(({ dictionary, loading }) => ({
  dictionary,
  loading: loading.effects['dictionary/fetch']
}))(Dictionary);
